# -*- coding: utf-8 -*-
# @Time    : 2016/9/13

from sympy import S
from mathsolver.functions.daoshu.daoshuyunsuan import HanShuDaoShuYunSuan
from mathsolver.functions.base import BaseFunction, new_latex, BaseSymbolValue, BaseIneq, BaseBelong
from mathsolver.functions.hanshu.dingyiyu import QiuDingYiYu
from mathsolver.functions.hanshu.helper import check_func
from mathsolver.functions.budengshi.jiebudengshi import JieBuDengShi
from mathsolver.functions.budengshi.params_ineqs_funcs import BaseParamerInterval


class HanShuDiZengQuJian(BaseFunction):
    """利用导数求函数的单调递增区间"""
    symbol1, symbol2 = ">", "增"
    flag = True

    def solver(self, *args):
        fun = check_func(args[0])

        # 求函数定义域
        dingyiyu = QiuDingYiYu().solver(fun)
        if dingyiyu != S.Reals:
            self.steps.append(["函数的定义域为： {}".format(new_latex(dingyiyu)), ""])

        # 求函数导数
        deriv = HanShuDaoShuYunSuan().solver(fun).output[0]
        self.steps.append(["因为 {}".format(fun.printing()),
                           "求导得 {}".format(deriv.printing())])

        for s1, s2 in zip(self.symbol1, self.symbol2):
            # 令导数大于0，或小于0
            solver = JieBuDengShi().solver(BaseIneq([str(deriv.expression), s1, '0'])).output[0]

            # 如果不含参，输出为 BaseSymbolValue
            if isinstance(solver, BaseSymbolValue):
                dandiaoqujian = solver.value.values()[0]
                self.steps.append(["令 {} {} 0".format(new_latex(deriv.expression), s1),
                                   "得：{} \\in {}".format(new_latex(deriv.var), new_latex(dandiaoqujian))])

                # 求定义域与单调区间的交集
                dandiaoqujian = dingyiyu.intersection(dandiaoqujian)

                if dingyiyu != S.Reals:
                    self.steps.append(["结合函数的定义域得 {} \\in {}".format(new_latex(deriv.var), new_latex(dandiaoqujian)), ""])

                self.steps.append(["所以函数的单调递{}区间是 {}".format(s2, new_latex(dandiaoqujian)), ""])
                self.output.append(dandiaoqujian)
            # 如果含参数，输出为 baseParamerInterval
            # e.g. baseParamerInterval({'var':'x', 'paramer_var':'a', 'solveset':((a的取值范围1, x的解集1), (a的取值范围2, x的解集2))})
            elif isinstance(solver, BaseParamerInterval):
                dandiaoqujian = []
                a = solver.value['paramer_var']
                solver_result = solver.value['solveset']
                for quzhi, jieji in solver_result:
                    self.steps.append(
                        ["当 %s \\in %s 时, 函数的单调%s区间为：%s" % (new_latex(a), new_latex(quzhi), s2, new_latex(jieji)), ""])
                    dandiaoqujian.append([BaseBelong([a, "\\in", quzhi]), dingyiyu.intersection(jieji)])
                self.output.append(dandiaoqujian)

        self.label.add("利用导数求函数的单调区间")
        return self


class HanShuDiJianQuJian(HanShuDiZengQuJian):
    """利用导数求函数的单调递减区间"""
    symbol1, symbol2 = "<", "减"


class HanShuDanDiaoQuJian(HanShuDiZengQuJian):
    """利用导数求函数的单调（递增，递减）区间"""
    symbol1, symbol2 = [">", "<"], ["增", "减"]


if __name__ == "__main__":
    pass
